﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Web.UI;
using EVideoDataService;
using VideoNetApplication.Common;
using VideoNetApplication.Common.CacheManager;
using VideoNetApplication.Common.Extension;
using VideoNetApplication.Common.Service;
using VideoNetApplication.Common.ViewModel;
using VideoNetApplication.Common.Web;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using System.Configuration;
using VideoNetApplication.Common.Helper;

namespace VideoNetApplication.Handler
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CalendarHandler : IHttpHandler
    {

        AjaxUtilJson rtn = new AjaxUtilJson();

        public void ProcessRequest(HttpContext context)
        {
            int SchoolId = 0;
            if (ConfigurationManager.AppSettings["IsConfig"] == "1")
            {
                if (HttpContext.Current.Request["SchoolId"] != null && StringUtils.IsNumeric(HttpContext.Current.Request["SchoolId"]))
                {
                    SchoolId = Convert.ToInt32(HttpContext.Current.Request["SchoolId"]);
                }
            }
            else
            {
                SchoolId = Convert.ToInt32(ConfigurationManager.AppSettings["SchoolID"]);
            }
            if (MembershipService.GetUser() == null)
            {
                CommonCacheManager.FlushCache();
                rtn.ReturnUrl = "../UserLogin.aspx?SchoolId=" + SchoolId + "&returnUrl=../UserCenter/UserCourseCalendar.aspx?SchoolId=" + SchoolId;

            }
            else
            {
                int currentY = 0;
                int currentM = 0;
                int currentMd = 0;
                var courseWeek = new CourseWeek();
                DateTime minTime = new DateTime();
                DateTime maxTime = new DateTime();
                string opType = context.Request.Form["OpType"];
                switch (opType)
                {

                    case "CalendarCourseList":
                        GetCourseList(context, SchoolId);
                        break;
                    case "PreWeek":
                        currentY = int.Parse(context.Request["CurrentY"]);
                        currentM = int.Parse(context.Request["CurrentM"]);
                        currentMd = int.Parse(context.Request["CurrentMd"]);
                        rtn.ResultMessage = courseWeek.GetCourseWeek(currentY, currentM, currentMd, 1, ref minTime, ref maxTime);
                        rtn.RtnMinYear = minTime.Year;
                        rtn.RtnMinMonth = minTime.Month;
                        rtn.RtnMinDay = minTime.Day;
                        rtn.RtnMaxYear = maxTime.Year;
                        rtn.RtnMaxMonth = maxTime.Month;
                        rtn.RtnMaxDay = maxTime.Day;
                        break;
                    case "NextWeek":
                        currentY = int.Parse(context.Request["CurrentY"]);
                        currentM = int.Parse(context.Request["CurrentM"]);
                        currentMd = int.Parse(context.Request["CurrentMd"]);
                        rtn.ResultMessage = courseWeek.GetCourseWeek(currentY, currentM, currentMd, 2, ref  minTime, ref  maxTime);
                        rtn.RtnMinYear = minTime.Year;
                        rtn.RtnMinMonth = minTime.Month;
                        rtn.RtnMinDay = minTime.Day;
                        rtn.RtnMaxYear = maxTime.Year;
                        rtn.RtnMaxMonth = maxTime.Month;
                        rtn.RtnMaxDay = maxTime.Day;
                        break;
                }


            }

            context.Response.ContentType = "text/json;charset=UTF-8;";
            context.Response.Write(rtn.ToJsonItem());
        }


        private void GetCourseList(HttpContext context, int SchoolId)
        {
            DateTime courseDate = DateTime.Parse(context.Request["CourseDate"]);
            DateTime startTime = DateTime.Parse(context.Request["StartTime"]);
            DateTime endTime = DateTime.Parse(context.Request["EndTime"]);
            int roomId = int.Parse(context.Request["RoomId"]);
            int CurrentPlay = 0;
            if(!string.IsNullOrEmpty(context.Request["CurrentIndex"]))
            {
                CurrentPlay = int.Parse(context.Request["CurrentIndex"]);
            }
            DateTime start = new DateTime(courseDate.Year, courseDate.Month, courseDate.Day, startTime.Hour, startTime.Minute, startTime.Second);
            DateTime end = new DateTime(courseDate.Year, courseDate.Month, courseDate.Day, endTime.Hour, endTime.Minute, endTime.Second);


            #region 绑定视频的相关信息
            int courseListId = int.Parse(context.Request["CourseID"]);
            CourseService courseHelper = new CourseService();

            DataSet ds = courseHelper.GetCourseDetailByDestId(SchoolId, courseListId);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                int cj = CurrentPlay + 1;
                DataRow dr = ds.Tables[0].Rows[0];
                rtn.TeacherName = dr["vt_realname"].ToString();
                rtn.CourseName = dr["vc_name"].ToString() + "&nbsp;第" + cj + "节";
                rtn.CourseDesc = dr["vc_desc"].ToString();

            }
            #endregion
            #region 获取视频的评论条数
            CommentService commentService = new CommentService();
            int commentCount = commentService.GetMessageCnt(courseListId);
            rtn.RtnCount = commentCount;
            #endregion

            VideoInfoService vi = new VideoInfoService();
            List<VFInfo> list = new List<VFInfo>();
            list = vi.GetVSInfoListByTimespan(SchoolId, roomId, start, end, VFType.SD);
            //List<VFInfo> list2= new List<VFInfo>();
            // IEnumerable<VFInfo>  list2= list.Distinct < List<VFInfo>>(list).ToList();


            ArrayList tempAL = new ArrayList();

            List<VFInfo> tempList = new List<VFInfo>();
            foreach (var vfInfo in list)
            {
                StringBuilder tempSB = new StringBuilder();
                tempSB.Append(vfInfo.VFUrl);
                tempSB.Append("\\");
                tempSB.Append(vfInfo.VFName);

                if (!tempAL.Contains(tempSB.ToString()))
                {
                    tempAL.Add((tempSB.ToString()));
                    tempList.Add(vfInfo);
                }

            }

            list = tempList.OrderBy(s=>s.VSTime).ToList();
            //通过webservice返回的视频地址列表 放入缓存 
            string js = string.Empty;
            StringBuilder sbHtml = new StringBuilder();
            string turl = context.Request.Url.ToString();
            if (turl.IndexOf("?showflvid=") > 0)
                turl = turl.Remove(context.Request.Url.ToString().IndexOf("?showflvid="));

            if (list.Count > 0)
            {
                sbHtml.AppendLine("<div class=\"playTable\">");
                for (int i = 0; i < list.Count; i++)
                { 

                    js = SetWhichVideoPlaying(list, CurrentPlay);
                    if (courseHelper.ChkExsit(Convert.ToInt32(list[CurrentPlay].VSID)) > 0)
                    {
                        js = "";
                    }
                    rtn.ReturnValue = js;

                    if (i % 8 == 0)
                    {
                        sbHtml.AppendLine("<ul>");
                    }
                    if (CurrentPlay == i)
                    {
                        sbHtml.AppendLine("<li> <a href=\"javascript:VideoPalyByIndex('" + i + "')\"><font color=red><strong>第" + (i + 1) +
                                          "段</strong></font></a></li>");
                    }
                    else
                    {
                        sbHtml.AppendLine("<li> <a href=\"javascript:VideoPalyByIndex('" + i + "')\">第" + (i + 1) +
                                              "段</a></li>");
                    }
                    if ((i + 1) % 8 == 0)
                    {
                        sbHtml.AppendLine("</ul>");
                    }


                }
                sbHtml.AppendLine("</div >");
                //添加用户观看日志
                StudentService service = new StudentService();
                service.AddUserLog(MembershipService.GetUser());

            }




            rtn.ResultMessage = sbHtml.ToString();

        
        }

        private string SetWhichVideoPlaying(List<VFInfo> list, int index)
        {
            StringBuilder sbHtml = new StringBuilder();
            string flvPath = list[index].VFUrl;
            string ImgPath = list[index].vpInfo.VPUrl;
            sbHtml.AppendLine("<script type='text/javascript'>    LoadPlayer('" + flvPath + "','" + ImgPath + "');</script>");
            return sbHtml.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
